//
//  StockAddVC.m
//  timelyRain
//
//  Created by Jiafei Wei on 16/8/15.
//  Copyright © 2016年 Jiafei Wei. All rights reserved.
//

#import "StockAddVC.h"
#import "MBTUiColor.h"
#import "HttpTool.h"
#import "StockTickerDetails.h"
#import "StockTicker.h"
#import "StockCodeCell.h"
#import "DbManage.h"

@interface StockAddVC ()<UIGestureRecognizerDelegate,UITableViewDelegate,UITableViewDataSource,UISearchControllerDelegate,UISearchResultsUpdating>
{
    DbManage *db;
}
@property (weak, nonatomic) IBOutlet UIView *staus;
@property (weak, nonatomic) IBOutlet UIView *nav;
@property (weak, nonatomic) IBOutlet UIView *left;
@property (weak, nonatomic) IBOutlet UIView *right;
@property (weak, nonatomic) IBOutlet UILabel *titleText;

@property (weak, nonatomic) IBOutlet UITableView *demoTableView;
@property (nonatomic ,strong)UISearchController *searchVC;
@property (nonatomic ,strong)NSMutableArray *exampleArr;
@property (nonatomic ,strong)NSMutableArray *searchArr;
@property (nonatomic ,strong)NSMutableArray *selectArr;
@property (nonatomic ,strong)NSMutableArray *haveArr;
@end

@implementation StockAddVC

- (void)viewDidLoad {
    [super viewDidLoad];
    db=[DbManage shareDbManage];
    [self setViewBG];
    [self complete];
    _demoTableView.delegate = self;
    _demoTableView.dataSource = self;
    [_demoTableView setAllowsSelectionDuringEditing:YES];
    self.view.backgroundColor = [UIColor whiteColor];
    _exampleArr =[NSMutableArray array];
    _searchArr =[NSMutableArray array];
    _selectArr =[NSMutableArray array];
    _haveArr =[db queryStock];
}

-(void)setViewBG{
    _titleText.text=@"添加自选股";
     self.navigationController.navigationBarHidden=YES;
    _staus.backgroundColor =[UIColor colorwithHexString:@"#1186D6"];
    _nav.backgroundColor =[UIColor colorwithHexString:@"#1186D6"];
    _left.backgroundColor =[UIColor colorwithHexString:@"#1186D6"];
    _right.backgroundColor =[UIColor colorwithHexString:@"#1186D6"];
}


-(void)complete{
    _left.userInteractionEnabled = YES;
    UITapGestureRecognizer *addTapGest = [[UITapGestureRecognizer alloc] init];
    addTapGest.numberOfTapsRequired = 1;
    addTapGest.delegate = self;
    [_left addGestureRecognizer:addTapGest];
    [addTapGest addTarget:self action:@selector(addTapView:)];
}
- (void)addTapView:(UITapGestureRecognizer *)addTapGest{
    self.searchVC.active=NO;
    [self.navigationController popViewControllerAnimated:YES];
}



- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath//cell
{
    static NSString *identify = @"cellIdentify";
    StockCodeCell *cell = [tableView dequeueReusableCellWithIdentifier:identify];
    if (cell == nil) {
        cell = [[[NSBundle mainBundle] loadNibNamed:@"StockCodeCell" owner:nil options:nil] lastObject];
    }
    StockTickerDetails *data = _searchArr[indexPath.row];
    cell.detail=data;
    UIImageView *image = cell.image;
    [image setUserInteractionEnabled:YES];
    image.tag =indexPath.row;
    
    UITapGestureRecognizer *imageTapGest = [[UITapGestureRecognizer alloc]init];
    imageTapGest.numberOfTapsRequired = 1;
    imageTapGest.delegate = self;
    [image addGestureRecognizer:imageTapGest];
    [imageTapGest addTarget:self action:@selector(imageTapView:)];
    return cell;
}
//
- (void)imageTapView:(UITapGestureRecognizer *)tapGest{//
    //重新加载指定行
    NSLog(@"leftTapView");
    NSInteger tag =tapGest.view.tag;
    StockTickerDetails *things =_searchArr[tag];//要这样做才行啊
    NSLog(@"things====: %@" ,things.have?@"YES":@"NO");
    if (things.have) {
        NSLog(@"++++====things.ticker%@",things.ticker);
        things.have=NO;
        [db deleteStockByCode:things.shortNM];
    }else{
        things.have=YES;
        StockCode *code =[[StockCode alloc]init];
        code.name=things.shortNM;
        if ([things.exchangeCD isEqualToString:@"XSHE"]) {//XSHE深圳 XSHG上海
            NSString *codename =@"sz";
            codename =[codename stringByAppendingString:things.ticker];
            code.stockcode =codename;
        }else{
            NSString *codename =@"sh";
            codename =[codename stringByAppendingString:things.ticker];
            code.stockcode =codename;
        }
        [db insertStock:code];
    }
    NSIndexPath *indexPath =[NSIndexPath indexPathForRow:tag inSection:0];
    [_demoTableView reloadRowsAtIndexPaths:@[indexPath]withRowAnimation:UITableViewRowAnimationNone];
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (self.searchVC.active) {
        return self.searchArr.count;//搜索结果
    }else
    {
        return self.exampleArr.count;//原始数据
    }
    //return self.exampleArr.count;
}

-(void)viewDidLayoutSubviews{
    
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    
}

- (void)updateSearchResultsForSearchController:(UISearchController *)searchController
{
    NSLog(@"updateSearchResultsForSearchController");
    NSString *searchString = [self.searchVC.searchBar text];
    [self getStockCode:searchString];
}

-(void)viewDidDisappear:(BOOL)animated{
    [super viewDidDisappear:YES];
}
- (UISearchController *)searchVC
{
    if (!_searchVC) {
        _searchVC = [[UISearchController alloc]initWithSearchResultsController:nil];
        _searchVC.searchResultsUpdater = self;
        _searchVC.dimsBackgroundDuringPresentation = NO;
        _searchVC.hidesNavigationBarDuringPresentation = YES;
        _searchVC.searchBar.frame = CGRectMake(self.searchVC.searchBar.frame.origin.x, self.searchVC.searchBar.frame.origin.y, self.searchVC.searchBar.frame.size.width, 44.0);
         [self.searchVC.searchBar setImage:[UIImage imageNamed:@"搜索"] forSearchBarIcon:UISearchBarIconSearch state:UIControlStateNormal];
        self.demoTableView.tableHeaderView = self.searchVC.searchBar;
    }
    return _searchVC;
}

-(void)getStockCode:(NSString *)text{//成功了
    //NSString *url =@"https://api.wmcloud.com/data/v1/api/master/getEquInfo.json?ticker=3000&pagesize=10&pagenum=1";
    NSString *url =@"https://api.wmcloud.com/data/v1/api/master/getEquInfo.json";
    NSDictionary *params = @{@"ticker":text,@"pagesize":@20,@"pagenum":@1};
    [HttpTool GET:url WithHeader:YES parameters:params success:^(id responseObject) {
        NSLog(@"成功了啊");
        StockTicker *text =[StockTicker mj_objectWithKeyValues:responseObject];
        NSLog(@"resultcode＝＝＝＝%@",text.retMsg);
        NSArray *resut=text.data;
        if (resut.count!=0) {//XSHE深圳 XSHG上海
            StockTickerDetails *dd =[resut objectAtIndex:0];
            NSLog(@"exchangeCD===%@",dd.exchangeCD);
        }
        [_searchArr removeAllObjects];
        [_searchArr addObjectsFromArray:resut];
        for (StockCode* s in _haveArr) {
            for (StockTickerDetails* a in _searchArr) {
                if ([s.stockcode containsString:a.ticker]) {
                    a.have=YES;//yes代表拥有
                }
            }
        }
         [self.demoTableView reloadData];
        } failure:^(NSError *error){
        NSLog(@"%@",error);
    }];
}

@end
